from FPDLCore.Interfaces import IManagerEvent
from FPDLCore.DownloadWorkerClient import DownloadWorkerClient

class WorkerManager(IManagerEvent):
    def __init__(self, sel):
        self.sel = sel
        self.workerlist = {}
        self.onworkerlist = []

    def dowork(self, remoteaddr, onworker):
        for k in self.workerlist.keys():
            if k.isidle():
                onworker(k)
                return

        self.onworkerlist.append(onworker)
        if not self.startworker(remoteaddr):
            onworker(False)

    def startworker(self, remoteaddr):
        cli = DownloadWorkerClient(self, remoteaddr, self.sel)
        if not cli.connect():
            print("WorkerManager can't start worker:", cli)
            return False
        return True

    def shutdown(self):
        for k in [key for key in self.workerlist.keys()]:
            k.close()

    def register(self, worker):
        self.workerlist[worker] = {}
        if len(self.onworkerlist) > 0:
            self.onworkerlist.pop(0)(worker)

    def unregister(self, worker):
        if worker in self.workerlist.keys():
            del self.workerlist[worker]

    def startfail(self, worker):
        # make connection fail
        if len(self.onworkerlist) > 0:
            self.onworkerlist.pop(0)(False)
